package ocr;

/**
 * @author 啊林
 * @date 2022/4/8
 * @time 20:34
 */

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.swing.filechooser.FileSystemView;
import javax.swing.text.Style;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 通用文字识别（高精度版）
 */
public class AccurateBasic {
    //桌面路径
    public static String path = getDesktopPath() + "/图片检测";
    public static SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
    public static String token = AuthService.getToken();
    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public static String accurateBasic(String pictureName, String pictureStyle) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
        try {
            // 本地文件路径
            String dataFormat = df.format(new Date());     //yyyyMMdd
            String filePath = path + "/" + dataFormat +"/"+pictureName + "." + pictureStyle;
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
//            String accessToken = "[24.7d26b52fdca45552e27ee65f1b962f09.2592000.1652014230.282335-25930692]";
            String accessToken = "["+token+"]";

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
//            JsonElement words_result = returnData.getAsJsonArray("words_result");
//            writeFile(path, pictureName, words_result.toString());
            List<String> list = new ArrayList<>();
            for (JsonElement words_result : returnData.getAsJsonArray("words_result")) {
                JsonElement word = words_result.getAsJsonObject().get("words");
                System.out.println(word);
                list.add(word.toString());
            }
            writeFile(path+"/"+dataFormat, pictureName,list);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *创建文件
     * @param filePath1 要创建的文件路径
     * @param fileName  要创建的文件名
     * @param list  写入文件的内容
     * @throws IOException
     */
    public static void createFile(String filePath1, String fileName, List<String> list) throws IOException {
        String filePath = filePath1;
        File dir = new File(filePath);
        // 一、检查放置文件的文件夹路径是否存在，不存在则创建
        if (!dir.exists()) {
            dir.mkdirs();// mkdirs创建多级目录
        }
        File checkFile = new File(filePath + "/" + fileName + ".txt");
        FileWriter writer = null;
        try {
            // 二、检查目标文件是否存在，不存在则创建
            if (!checkFile.exists()) {
                checkFile.createNewFile();// 创建目标文件
            }
            // 三、向目标文件中写入内容
            // FileWriter(File file, boolean append)，append为true时为追加模式，false或缺省则为覆盖模式
            writer = new FileWriter(checkFile, true);
            for (String s : list) {
                writer.append(s+"\n");  //每行写一个单词
            }
            writer.append(" "+"\n");    //最末尾换行
            writer.flush();
            System.out.println("写入成功！！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != writer) {
                writer.close();
            }
        }
    }

    public static void writeFile(String path, String fileName, List<String> data) {
        try {
//            StringBuffer stringBuffer = new StringBuffer(data);
            createFile(path, fileName, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取桌面路径
     *
     * @return
     */
    public static String getDesktopPath() {
        char c = '\\';
        String s = Character.toString(c);
        FileSystemView fsv = FileSystemView.getFileSystemView();
        File com = fsv.getHomeDirectory();
        return com.getPath().replace(s, "/");
    }

    public static void main(String[] args) {
        accurateBasic("5", "jpg");
//        accurateBasic("19-45-27", "bmp");
    }


}
